#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date    : Tue Jul 16 2019
# @Author  : xujunfu (xjf891121@gmail.com})
# @Link    : http://junfuxu.github.io/
from django.db.models import Q

from alarm.models import Alarm
from dispatcher.zsh.const import YB2ZSH_MAP

from .base import BaseDispatcher


class AlarmDispatcher(BaseDispatcher):

    def __init__(self, *args, **kwargs):
        return super().__init__(*args, **kwargs)

    def start(self):
        try:
            self.send_info()
        except Exception as e:
            print(e)

        self.dump_status()

    def send_info(self):
        event_list = []
        media_list = {
            "Pictures": [],
            "Videos": []
        }
        alarm_infos = Alarm.objects.filter(Q(id__gt=self.current_status['vehicleEvent']) & Q(vehicle__in=self.vehicle_infos.keys())).order_by("id")[0:self.LIMIT]
        for alarm_info in alarm_infos:
            if alarm_info:
                warn_info = {
                    'eid': f'{self.VENDER_CODE}_{alarm_info.id}',
                    'vno': self.vehicle_infos[alarm_info.vehicle_id],
                    'color': '黄',
                    'type': YB2ZSH_MAP.get(alarm_info.category, '0x00'),
                    "driver": "",
                    'create_time': alarm_info.created_time.strftime(self.FORMAT_DT),
                }

                event = {
                    'dispatchNo': "",
                    'start_time': alarm_info.start_time,
                    'end_time': alarm_info.start_time,
                    'coordinate': 'WGS84',
                    'start_lng': str(alarm_info.location.longitude) if alarm_info.location.longitude else "",
                    'start_lat': str(alarm_info.location.latitude) if alarm_info.location.latitude else "",
                    'end_lng': '',  # 非必填
                    'end_lat': '',  # 非必填
                    'speed': float(alarm_info.location.speed) if alarm_info.location.speed else 0,
                    'eventGrade': '1',
                    'update_time': '',  # 非必填
                    'source ': self.VENDER_CODE,
                    'reserve1': '',
                    'reserve2': ''
                }
                media_category = "Videos" if alarm_info.media_uri_category == 2 else "Pictures"

                url_info = {
                    media_category: [
                        {
                            "channel": "",
                            "desc": '',
                            "url": alarm_info.media_uri,
                        }
                    ]
                }

                # 整合报警信息
                event.update(warn_info)
                event_list.append(event)

                # 整合图片和报警信息
                warn_info['data'] = url_info
                media_list[media_category].append(warn_info)

                # 记录最后一条id
                self.current_status['vehicleEvent'] = alarm_info.id

        # 发送事件
        self.send('vehicleEvent', event_list)

        # 发送图片/图片
        # 发送事件
        self.send('vehicleEventPicture', media_list['Pictures'])
        self.send("vehicleEventVideo", media_list['Videos'])
